<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="jobId" prop="jobId" v-show="false">
        <el-input v-model="queryParams.jobId" placeholder="请输入应用名称"" clearable size=" small" style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="应用名称" prop="appNmae">
        <el-input v-model="queryParams.appNmae" placeholder="请输入应用名称"" clearable size=" small" style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="Job名称" prop="jobName">
        <el-input v-model="queryParams.jobName" placeholder="请输入Job名称"" clearable size=" small" style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-circle-check" size="mini" @click="handAdd()">新增
        </el-button>
        <el-button type="success" plain icon="el-icon-circle-check" size="mini" :disabled="multiple"
          @click="handleStart()">开始
        </el-button>
        <el-button type="danger" plain icon="el-icon-circle-close" size="mini" :disabled="multiple"
          @click="handleStop()">暂停
        </el-button>
        <el-button type="info" plain icon="el-icon-copy-document" size="mini" :disabled="multiple"
          @click="handleCopy()">复制
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="jobInstanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="机器Ip" prop="machineIp" width="120" />
      <el-table-column label="应用名称" prop="appName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="任务名称" prop="jobName" width="100" />
      <el-table-column label="应用端口" prop="port" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="基础访问路径" prop="basePath" width="100" />
      <el-table-column label="任务名称" prop="jobName" width="100" />
      <el-table-column prop="jobStatus" label="Job状态">
        <template slot-scope="scope">
          <el-button type="success" size="mini" v-if="scope.row.serverStatus == 0 && scope.row.jobStatus == 0" round>
            任务运行中</el-button>
          <el-button type="info" size="mini" v-if="scope.row.serverStatus == 0 && scope.row.jobStatus == 1" round>任务暂停中
          </el-button>
          <el-button type="danger" size="mini" v-if="scope.row.serverStatus == 1 && scope.row.jobStatus== 0" round>
            服务宕机(重启运行)</el-button>
          <el-button type="danger" size="mini" v-if="scope.row.serverStatus == 1 && scope.row.jobStatus== 1" round>
            服务宕机(重启暂停)</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="serverStatus" label="应用状态">
        <template slot-scope="scope">
          <el-button type="success" size="mini" v-if="scope.row.serverStatus == 0" round>应用运行中</el-button>
          <el-button type="info" size="mini" v-if="scope.row.serverStatus == 1" round>应用宕机中</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="节点顺序">
        <template slot-scope="scope">
          <span v-if="scope.row.serverStatus == 0  && scope.row.jobStatus == 0">{{scope.row.sort}}</span>
        </template>
      </el-table-column>
      <el-table-column label="集群参数示例(默认下次执行)" :formatter="formatterParams" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-position" @click="lookJobLogs(scope.row.machineId)">服务启停日志
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-loading" @click="lookRunLogs(scope.row.machineId)">实例运行日志
          </el-button>
        </template>
      </el-table-column>

    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="pageLimit.pageNum" :limit.sync="pageLimit.pageSize"
      @pagination="getList" />


    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="机器Ip" prop="machineIp">
          <el-input v-model="form.machineIp" placeholder="请输入机器Ip" />
        </el-form-item>
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="form.appName" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="应用端口" prop="port">
          <el-input v-model="form.port" placeholder="请输入应用端口" />
        </el-form-item>
        <el-form-item label="Job名称" prop="jobName">
          <el-input v-model="form.jobName" placeholder="请输入Job名称" />
        </el-form-item>
        <el-form-item label="基础访问路径" prop="basePath">
          <el-input v-model="form.basePath" placeholder="请输入基础访问路径" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <!-- <el-button @click="cancel">取 消</el-button> -->
      </div>
    </el-dialog>
  </div>


</template>

<script>
  import {
    listJobInstance,
    delJobInstance,
    stopJobInstance,
    startJobInstance,
    copyJobInstance,
    addJobInstance

  } from "@/api/job/jobInstance";
  export default {
    name: "JobInstance",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 角色表格数据
        jobInstanceList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层（数据权限）

        // 日期范围
        dateRange: [],
        statusOptions: [],
        // 查询参数
        queryParams: {},
        pageLimit: {
          pageSize: 10,
          pageNum: 1
        },
        // 表单参数
        form: {

        },
        defaultProps: {
          children: "children",
          label: "label"
        },
      };
    },
    created() {
      this.queryParams.jobId = this.$route.query.jobId;
      this.getList();
    },
    methods: {
      /**
       * 查看运行日志
       * @param {Object} instanceId
       */
      lookRunLogs(instanceId) {
        this.$router.push({
          path: '/job/runlogs',
          query: {
            "instanceId": instanceId
          }
        })
      },

      /**
       * 服务启停日志
       * @param {Object} jobId
       */
      lookJobLogs(instanceId) {
        this.$router.push({
          path: '/job/jobInstancelog',
          query: {
            "instanceId": instanceId
          }
        })
      },

      /**
       * @param {Object} row 格式化示例参数
       */
      formatterParams(row) {
        if (row.serverStatus == 0 && row.jobStatus == 0) {
          return JSON.stringify(row.params)
        }
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        console.log(this.queryParams)
        listJobInstance(this.queryParams, this.pageLimit).then(
          response => {
            this.jobInstanceList = response.data.list;
            this.total = response.data.total;
            this.loading = false;
          }
        );
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.machineId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },

      /**
       * 删除
       * @param {Object} row
       */
      handleDelete(row) {
        const jobInstanceId = row.jobInstanceId || this.ids;
        alert(jobInstanceId);
      },


      // 表单重置
      reset() {
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.pageLimit.pageNum = 1;
        this.pageLimit.pageSize = 10;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },



      /**
       * 任务停止
       */
      handleStop() {
        let mIds = this.ids;
        this.$confirm('是否确认暂停这' + this.ids.length + '条数据?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return stopJobInstance(mIds);
        }).then(() => {
          this.msgSuccess("暂停成功");
          this.getList();
        })
      },

      /**
       * 任务开始
       */
      handleStart() {
        let mIds = this.ids;
        this.$confirm('是否确认开始这' + this.ids.length + '条数据?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return startJobInstance(mIds);
        }).then(() => {
          this.msgSuccess("开始成功");
          this.getList();
        })

      },
      /**
       * 复制实例
       */
      handleCopy() {
        let mIds = this.ids;
        if (mIds.length > 1) {
          this.msgError("目前仅支持单个实例");
          return;
        }
        let jobInstance;
        for (let temp of this.jobInstanceList) {
          if (temp.machineId === mIds[0]) {
            jobInstance = temp;
            break;
          }
        }
        if (jobInstance.jobStatus !== 0) {
          this.msgError("目前仅支持复制运行中的实例");
          return;
        }
        this.reset();
        //根据Id查询Job实例
        this.form.machineId = jobInstance.machineId;
        this.form.machineIp = jobInstance.machineIp;
        this.form.appName = jobInstance.appName;
        this.form.port = jobInstance.port;
        this.form.basePath = jobInstance.basePath;
        // this.form.jobName = jobInstance.jobName;
        this.open = true;
        this.title = "实例复制"
      },

      handAdd() {
        this.open = true;
        this.form = {};
        this.form.jobId = this.queryParams.jobId;
      },
      /**
       * 表单提交
       */
      submitForm() {
        console.log(this.form.machineId)
        if ((typeof this.form.machineId) == 'undefined' || this.form.machineId == '') {
          addJobInstance(this.form).then(response => {
            this.msgSuccess("复制成功");
            this.open = false;
            this.getList();
          });
        } else {
          copyJobInstance(this.form).then(response => {
            this.msgSuccess("复制成功");
            this.open = false;
            this.getList();
          });
        }


      }
    },

  };
</script>
